<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$debug=false;
if (isset($_GET['debug'])) $debug=$_GET['debug'];

// ------------ lixlpixel recursive PHP functions -------------
// scan_directory_recursively( directory to scan, filter )
// expects path to directory and optional an extension to filter
// ------------------------------------------------------------



/*
Note about the easy and simple progress check

The main method in that class works recurively.
That means that @each pass of recursion, it can find new directories and it knows how many files he has to analyze.
So: How many file just analyzed / all files including the ones to be analyzed... represents the progress
 (and obviously it MUST change during the scan)

*/

/*
Note about the operation_status table

The purpose was - at the beginning - to make 
1. an accurate control of the status of the analysis
2. a method to avoid circularity (with linux link and windows junctions)
3. a precise progress check

Currently this target is too complicated and time-wasting so I postpone the development
Instead of that, I'm going to develop an easier progress check (look at the previous note...)


*/


class deeperAbyss 
{
	var $count;
	var $id;
	var $level;
	var $directory_id;
	var $parent_dir_id;
	var $mysqli;
	var $parent_operation;
	var $current_operation;
	var $dirCounterId;
	var $fileCounterId;
	var $dirCounterNumber_id;
	var $fileCounterNumber_id;
	var $debug; 
	
	var $fileCounterNumber; //added to resolve the error  Undefined property: deeperAbyss::$fileCounterNumber in D:\_DATI_CONDIVISI\01. SVILUPPO\lander3\lander.php on line 201
	
	function deeperAbyss($mysqli){
		
		$this->count=0;
		$this->id=0;
		$this->level=-1;
		$this->directory_id =-1;
		$this->parent_dir_id =-1;
		$this->mysqli = $mysqli;
		$this->dirCounterNumber_id=null;
		$this->fileCounterNumber_id=null;
		$this->current_directory_id=null;
		$this->debug=true;
		if (isset($_GET['debug'])) $this->debug=$_GET['debug'];
		//making the dirCounterId as a empty string, make the insert queries working with autoincrement
		$this->dirCounterId="";
	
		
		
	
		//$this->mysqli->query("insert into operation_status values (NULL, '0','0',null, now())");	
		//$this->parent_operation=mysql_insert_id(); 
		//$this->parent_operation=$this->mysqli->insert_id;
		//$this->current_operation=mysql_insert_id(); 
		//$this->current_operation=$this->mysqli->insert_id;
		
		/******************************************************************************/
		/*	
		
			The operation_status system works in this way:
			
			At every operation a record is written.
			At every change of status the record is updated.
			A reference to the current operation is maintained.
			A reference to the first operation is maintained (this is useful in order to
			distinguish a cycle of landing from another one)
			
			                                                                          */
		/******************************************************************************/	
		
		//updating last operation
		//$this->mysqli->query("update operation_status set status = '1' where operation_status_id = '".$this->current_operation."'");	
		//creating next operation
		//$this->mysqli->query("insert into operation_status values (NULL,'1','0', ".$this->parent_operation.", now())");	
		
		
		/*retrieves a new operation_id carachterizing the action*/
		$this->mysqli->query("insert into operation values (NULL, now(), NULL);");	
		$this->current_operation=$this->mysqli->insert_id;
		$_SESSION['current_operation']=$this->current_operation;
		$this->mysqli->query("insert into operation_status values (NULL, '" . $this->current_operation . "', 'BEGIN', 'OK',  -1, now());");			 

		$this->mysqli->query("insert into operation_status values (NULL, '" . $this->current_operation . "', 'FILES', '0',  -1, now());");			 		 
		$this->dirCounterNumber_id = $this->mysqli->insert_id;
		$this->mysqli->query("insert into operation_status values (NULL, '" . $this->current_operation . "', 'DIRS', '0',  -1, now());");			 		 
		$this->fileCounterNumber_id = $this->mysqli->insert_id;
 				
	}		
	
	/*makes the value Apostrophe safe, doubling them*/
	function safeQuery($value){
		return str_replace("'", "''",$value);
	}

	function scan_directory_recursively($directory, $filter=FALSE ){ //, $parent_dir_id){
		set_time_limit(0) ;

		
		$this->mysqli->query("insert into directories values (NULL, '".$this->safeQuery($directory)."')");
		$current_directory_id = $this->mysqli->insert_id;
		$this->directory_id =$current_directory_id; 
		
		/*setting a time limit. ten seconds after reaching the $__filelimits*/
			
		$__filelimits = 10000;
		if  ($this->count<$__filelimits) set_time_limit (10);
		
		/**temporary parent directory*/
		 
		/*Puts the current parent directory in a temporary variable in order to keep it for the future....*/
		$temp_parent_dir_id = $this->parent_dir_id;		
		
		$this->level+=1;
		
		
		if(substr($directory,-1) == '/'){
			$directory = substr($directory,0,-1);
		}
		if(!file_exists($directory) || !is_dir($directory)){
			return FALSE;
		}
		elseif(is_readable($directory)){
			
			$directory_list = opendir($directory);
			$directory_tree = array();
			
			
			$printafter=12;
			
			while($file = readdir($directory_list))
			{
				if($file != '.' && $file != '..')
				{
					$this->count++;
					if (($this->count%$printafter)==0){
					if ($this->debug)  "Scanned:".$this->count."\n";
					flush();
					}	
					
					$path = $directory.'/'.$file;
					if(is_readable($path))
					{
						$subdirectories = explode('/',$path);
						if(is_dir($path))
						{
						
						
							/**updates the status info*/
							$this->dirCounterNumber++;						
							//LOGS THE INCREMENT OF DIRECTORY COUNT
							if ($this->debug)  "<li>"."insert into operation_status values ('".$this->fileCounterNumber_id."', '" . $this->current_operation . "', 'DIRS', '1',  -1, now()) ON DUPLICATE KEY UPDATE value = ".$this->dirCounterNumber.";";
							$this->mysqli->query("insert into operation_status values ('".$this->fileCounterNumber_id."', '" . $this->current_operation . "', 'DIRS', '1',  -1, now()) ON DUPLICATE KEY UPDATE value = ".$this->dirCounterNumber.";");			 
							
						
							$sql="insert into  `lander`.`files`
							 (
									`file_id` ,
									`operation_id` ,
									`drive` ,
									`level` ,
									`isdir` ,
									`directory_id` ,
									`parent_dir_id` ,
									`name` ,
									`stamp_creation` ,
									`byte_size` ,
									`extension`
									)
									VALUES (
									NULL, '".$this->current_operation."', 'd', '".$this->level."', '1', '".$this->directory_id."', '".$this->parent_dir_id."', 
									'".$this->safeQuery(end($subdirectories))."', '',
									'', ''
									);
							";
							
							
							$this->mysqli->query($sql);
							$this->id = $this->mysqli->insert_id;
							

							if ($this->debug)  "<li>(".$this->level.") - ".$path;
							if ($this->debug)  "<li>".$sql;
							if ($this->debug)  "<li>".$this->mysqli->error;
							flush();
	 


						/*Puts the current parent directory in a temporary variable in order to keep it for the future....*/
						$temp_parent_dir_id = $this->parent_dir_id;						
						/**Sets the parent as the current before calling scan_directory_recursively again*/
						$this->parent_dir_id = $this->id;										
						
						$this->scan_directory_recursively($path, $filter); //, $parent_dir_id);	
						
						/**Restores the control variables before exiting 'while' cycle*/
						$this->parent_dir_id = $temp_parent_dir_id;		
						
						}
						elseif(is_file($path))
						{
						
						/**updates the status info*/						
						$this->fileCounterNumber++;
						//LOGS THE INCREMENT OF FILE COUNT
						if ($this->debug)  "<li>"."insert into operation_status values ('".$this->dirCounterNumber_id."', '" . $this->current_operation . "', 'FILES', '1',  -1, now()) ON DUPLICATE KEY UPDATE value = '".$this->fileCounterNumber."';";
						
						$this->mysqli->query("insert into operation_status values ('".$this->dirCounterNumber_id."', '" . $this->current_operation . "', 'FILES', '1',  -1, now()) ON DUPLICATE KEY UPDATE value = '".$this->fileCounterNumber."';");			 
							
						/**Restores parent_dir_id because previous "scan_directory_recursively" calls could changed it*/
						$this->parent_dir_id = $temp_parent_dir_id;								
							
							if ($this->debug)  "<li>(".$this->level.") - ".$path;
							flush();
 
							$exp=explode('.',end($subdirectories));
							$extension = $exp[count($exp)-1];
 
							$sql="insert into  `lander`.`files`
							 (
									`file_id` ,
									`operation_id` ,
									`drive` ,
									`level` ,
									`isdir` ,		
									`directory_id` ,
									`parent_dir_id` ,
									`name` ,
									`stamp_creation` ,
									`byte_size` ,
									`extension`
									)
									VALUES (
									NULL, '".$this->current_operation."', 'd', '".$this->level."', '0', '".$this->directory_id."', '".$this->parent_dir_id."', 
									'".$this->safeQuery(end($subdirectories))."', '".filemtime  ($path)."',
									'".filesize($path)."', '".$this->safeQuery($extension)."'
									);
							";
	 
							
							$this->mysqli->query($sql);
							
							$this->id = $this->mysqli->insert_id;
							 
							if ($this->debug)  "<li>".$this->mysqli->error;
							
							
						}
					}
				}
			}
			closedir($directory_list); 
			
			/**Restores the control variables before exiting function*/
			$this->level-=1;	
			$this->parent_dir_id = $temp_parent_dir_id;		
			
			return $directory_tree;
		}else{
			$this->level-=1;	
			$this->parent_dir_id = $temp_parent_dir_id;		
			return FALSE;	
		}
		
		
	}
}

/*
// hostname
$dbhost = "localhost";  
// utente per la connessione a MySQL 
$dbuser = "root";
// password per l'autenticazione dell'utente
$dbpassword = "";
// connessione tramite mysql_connect()
$dbname = "lander";

$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);

$da = new deeperAbyss($mysqli);

//$mysqli->query("truncate table files");
 
 
		//LOG THE END OF TASK
		if (! ($dtree = $da->scan_directory_recursively('./../../../6. Eclipse',false))){
			$da->mysqli->query("insert into operation_status values (NULL, '" . $da->current_operation . "', 'END', 'OK',  -1, now());");			 
		}
		else {
			$da->mysqli->query("insert into operation_status values (NULL, '" . $da->current_operation . "', 'END', 'BAD',  -1, now());");			 
		}



 */


// ------------------------------------------------------------

?>